package com.vogue.supplymall.order.domain.service.impl;

import javax.annotation.Resource;

import com.vogue.supplymall.common.domain.dto.CommentImgInfo;
import com.vogue.supplymall.common.domain.dto.CommentInfo;
import com.vogue.supplymall.common.domain.dto.RelevanceInfo;
import com.vogue.supplymall.common.domain.dto.UploadInfo;
import com.vogue.supplymall.common.domain.dto.UserInfo;

import com.vogue.supplymall.shop.domain.service.OrganShopImgService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.vogue.ssm.database.dao.BaseDao;
import com.vogue.supplymall.order.domain.dao.CommentDao;
import com.vogue.supplymall.order.domain.dao.CommentImgDao;
import com.vogue.supplymall.order.domain.model.Comment;
import com.vogue.supplymall.order.domain.model.CommentDetail;
import com.vogue.supplymall.order.domain.model.CommentImg;
import com.vogue.supplymall.order.domain.service.CommentDetailService;
import com.vogue.supplymall.order.domain.service.CommentImgService;
import com.vogue.supplymall.order.domain.service.CommentService;
import com.vogue.supplymall.order.domain.service.OrderService;
import com.vogue.supplymall.order.exception.AddOrUpdateCommentException;
import com.vogue.supplymall.upload.domain.service.UploadService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("commentService")
public class CommentServiceImpl extends BaseServiceImpl<Comment, Long> implements CommentService {

    public static final Logger LOGGER_COMMENTSERVICEIMPL = LoggerFactory.getLogger(CommentServiceImpl.class);
    
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private CommentDao commentDao;
    @Resource
    private CommentDetailService commentDetailService;
    @Resource
    private UploadService uploadService;
    @Resource
    private CommentImgDao commentImgDao;
    @Resource
    private CommentImgService commentImgService;

    @Resource
    private OrderService orderService;

    public CommentServiceImpl(BaseDao<Comment, Long> baseDao) {
        super(baseDao);
    }

    @Override
    public Map<String, Object> saveOrUpdateCommentInfo(CommentInfo commentInfo, UserInfo info) {
        Map<String, Object> resultMap = new HashMap<>();

        int type = commentInfo.getType();

        if (type == 0) {        //新增
            try {
                resultMap = this.saveCommentInfo(commentInfo, info);

                boolean resultFlag = (boolean) resultMap.get("resultFlag");
                if (!resultFlag) {
                    throw new AddOrUpdateCommentException("新增");
                }

            } catch (Exception e) {
                LOGGER_COMMENTSERVICEIMPL.info("新增商品评价失败");
                e.printStackTrace();
                throw new AddOrUpdateCommentException("新增");
            }

        } else {                //更新
            try {
                this.updateCommentDetail(commentInfo);
            } catch (Exception e) {
                LOGGER_COMMENTSERVICEIMPL.info("更新商品评价失败");
                e.printStackTrace();
                throw new AddOrUpdateCommentException("更新");
            }

        }

        return null;
    }

    /**
     * 新增评价
     */
    public Map<String, Object> saveCommentInfo(CommentInfo commentInfo, UserInfo info) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        boolean resultFlag = true;

        if (commentInfo.getCommentobejct() == 0) {        //买家评价，用户信息为买家信息

            if (commentInfo.getCommentid() == null || commentInfo.getCommentid() == 0) {    //主表是新增
                resultMap = this.saveComment(commentInfo, info);

            } else {                                                                //主表不变，明细表新增，即追加评价
                try {
                    resultMap = this.saveCommentDetail(commentInfo, commentInfo.getCommentid());
                } catch (Exception e) {
                    resultFlag = false;
                    resultMap.put("resultFlag", resultFlag);
                    LOGGER_COMMENTSERVICEIMPL.info("保存明细表失败");
                    e.printStackTrace();
                }
            }

        } else {                                        //卖家评价，主表不变，明细表新增，即回复买家评价
            try {
                resultMap = this.saveCommentDetail(commentInfo, commentInfo.getCommentid());
            } catch (Exception e) {
                resultFlag = false;
                resultMap.put("resultFlag", resultFlag);
                LOGGER_COMMENTSERVICEIMPL.info("回复买家评价失败");
                e.printStackTrace();
            }
        }


        return resultMap;
    }

    /**
     * 保存评价主表
     */
    public Map<String, Object> saveComment(CommentInfo commentInfo, UserInfo info) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        boolean resultFlag = true;
        Date date = new Date();

        Comment comment = new Comment();
        
        if(commentInfo.getCommentobejct() == 0) {		//买家
        	comment.setRestoreflag(0);
        }else {											//卖家
        	comment.setRestoreflag(comment.getRestoreflag());
        }
        
        comment.setOrderid(commentInfo.getOrderid());
        comment.setOrdernumber(commentInfo.getOrdernumber());
        comment.setShopid(commentInfo.getShopid());
        comment.setShopname(commentInfo.getShopname());
        comment.setOrderdate(sdf.parse(commentInfo.getOrderdate().toString()));
        comment.setProductid(commentInfo.getProductid());
        comment.setProductname(commentInfo.getProductname());
        comment.setProductimgurl(commentInfo.getProductimgurl());
        comment.setCommentmark(commentInfo.getCommentmark());
        comment.setHiddenflag(commentInfo.getHiddenflag());
        comment.setCreateDate(date);
        comment.setModifyDate(date);
        comment.setBuyerid(info.getLoginId());
        comment.setBuyername(info.getName());
        comment.setBurersyscodeid(info.getSyscodeid());
        comment.setSellersyscodeid(commentInfo.getSellersyscodeid());
        commentDao.save(comment);

        //保存明细表
        try {
            commentInfo.setCommentid(comment.getId());
            this.saveCommentDetail(commentInfo, comment.getId());
        } catch (Exception e) {
            resultFlag = false;
            LOGGER_COMMENTSERVICEIMPL.info("保存明细表失败");
            e.printStackTrace();
            throw new RuntimeException();
        }


        if(resultFlag) {
	        //将订单置为已评价状态
	        try {
	            orderService.updateOrderCommentFlag(commentInfo.getOrderid(), commentInfo.getProductid(), 1);
	        } catch (Exception e) {
	            resultFlag = false;
	            LOGGER_COMMENTSERVICEIMPL.info("置订单状态失败");
	            e.printStackTrace();
	            throw new RuntimeException();
	        }
        }
        
        resultMap.put("resultFlag", resultFlag);

        return resultMap;
    }
    /**
     * 保存评价明细表
     */
    public Map<String, Object> saveCommentDetail(CommentInfo commentInfo, Long commentId) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> paramMap=new HashMap<>();
        boolean resultFlag = true;
        Date date = new Date();

        CommentDetail cd = new CommentDetail();
        cd.setCommentid(commentInfo.getCommentid());
        cd.setCommentobejct(commentInfo.getCommentobejct());
        cd.setCommenttext(commentInfo.getCommenttext());
        cd.setAnswerflag(0);
        cd.setReadflag(0);
        cd.setDefaultanswerflag(commentInfo.getDefaultanswerflag());
        cd.setCreateDate(date);
        cd.setModifyDate(date);

        commentDetailService.save(cd);

        //如果是卖家回复评价，则需要将买家评价置为已回复，如果是买家评价，需要保存图片
        if(commentInfo.getCommentobejct() == 1) {
	        paramMap.put("commentId", commentId);
	        paramMap.put("answerFlag", 1);
	        
	        try {
				
	        	this.update0(commentDao.setValueForAnswerFlag(), paramMap);
			} catch (Exception e) {
				resultFlag = false;
	            LOGGER_COMMENTSERVICEIMPL.info("置买家回复标记失败");
	            e.printStackTrace();
	            throw new RuntimeException(e);
			}
	        
        }else {        
	        //保存评价图片
	        try {
	        	
	            this.saveCommentImgInfo(commentInfo.getCommentImgInfo(), commentId, cd.getId(), commentInfo.getShopid(),commentInfo.getOrderid());
	        } catch (Exception e) {
	            resultFlag = false;
	            LOGGER_COMMENTSERVICEIMPL.info("保存明细表图片失败");
	            e.printStackTrace();
	            throw new RuntimeException(e);
	        }
        }
        
        resultMap.put("resultFlag", resultFlag);

        return resultMap;
    }

    /**
     * 更新评价明细表，如果卖家已读，已回复，修改后该评论状态不变
     */
    public void updateCommentDetail(CommentInfo commentInfo) throws Exception {
        Date date = new Date();

        Long detailId = commentInfo.getDetailid();
        CommentDetail cd = commentDetailService.get(detailId);
       String a= commentInfo.getCommenttext();
        cd.setCommenttext(commentInfo.getCommenttext());
        cd.setModifyDate(date);

        commentDetailService.update(cd);

        //修改图片信息
        if (commentInfo.getCommentobejct() == 0) {

        	this.saveCommentImgInfo(commentInfo.getCommentImgInfo(), cd.getCommentid(), detailId, commentInfo.getShopid(),commentInfo.getShopid());
        }

    }

    /**
     * 保存评价图片
     */
    public void saveCommentImgInfo(List<CommentImgInfo> ciList, Long commentId, Long detailId, Long shopId,Long orderId) throws Exception {

        //先删除本地图片信息
        commentImgService.delteCommentImg(detailId);

        if(ciList.size()>0&&ciList.get(0)!=null) {
	        for (CommentImgInfo cii : ciList) {
	            //如果发现图片是临时路径则重新上传生成正式的
	            if (cii.getUrl().contains("/"
	                    + com.vogue.supplymall.common.constant.ConstantBean.SYSTEM_NAME
	                    + "/" + UploadService.TEMP_PATH)) {
	                UploadInfo uploadInfo = new UploadInfo();
	
	                //拼接数据唯一id（评价明细id+图片顺序号）
	                //Long dataid = Long.valueOf(((detailId + "") + (cii.getImgsort() + "")));
	
	                uploadInfo.setDataid(orderId);
	                uploadInfo.setSourcepath(cii.getUrl());    //图片地址
	                if (cii.getUrl().contains(".")) {
	                    uploadInfo.setExtension(cii.getUrl().substring(cii.getUrl().lastIndexOf(".") + 1));    //图片扩展名
	                }
	
	                //区分模块名
	                uploadInfo.setModuleName(
	                        com.vogue.supplymall.upload.domain.bean.ConstantBean.PRODUCT_COMMENT_IMG_NAME
	                                + "/" + shopId
	                                + "/" + detailId);
	
	                //上传图片信息到青云
	                String url = uploadService.uploadResource(uploadInfo);
	
	                //保存图片信息到本地
	                this.saveCommentImg(cii, commentId, detailId, url);
	            } else {
	                //保存图片信息到本地
	                this.saveCommentImg(cii, commentId, detailId, cii.getUrl());
	            }
	
	        }
        }
    }

    /**
     * 保存商品图片信息
     */
    public void saveCommentImg(CommentImgInfo cii, Long commentId, Long detailId, String url) {
        Date date = new Date();

        CommentImg ci = new CommentImg();
        ci.setCommentid(commentId);
        ci.setCommentdetailid(detailId);
        ci.setType(cii.getType());
        ci.setImgsort(cii.getImgsort());
        ci.setUrl(url);
        ci.setCreateDate(date);
        ci.setModifyDate(date);

        commentImgDao.save(ci);
    }

    @Override
    public Map<String, Object> getCommentingCount(RelevanceInfo relevanceInfo) {
        return commentDao.getCommentingCount(relevanceInfo);
    }
    @Override
    public Map<String, Object> getCommentingCount(CommentInfo commentInfo) {
        return commentDao.getCommentingCount(commentInfo);
    }

    @Override
    public Map<String, Object> getFinishCommentCount(RelevanceInfo relevanceInfo) {
        return commentDao.getFinishCommentCount(relevanceInfo);
    }

    @Override
    public Map<String, Object> findBuyerCommentList(CommentInfo commentInfo) {
        List<Map<String, Object>> result = commentDao.findBuyerCommentList(commentInfo);
        LOGGER_COMMENTSERVICEIMPL.info("findBuyerCommentList >> result.size : " + result.size());

        RelevanceInfo relevanceInfo = new RelevanceInfo();
        relevanceInfo.setUserId(commentInfo.getLoginId());
        relevanceInfo.setSyscodeid(commentInfo.getSyscodeid());
        relevanceInfo.setOrganid(commentInfo.getOrganid());
        //待评价数量
        Map<String, Object> commentingCount = this.getCommentingCount(relevanceInfo);
        //已评价数量
        Map<String, Object> fishCommentCount = this.getFinishCommentCount(relevanceInfo);

        Map<String, Object> map = new HashMap<>();
        map.put("commentDataList", result);
        map.putAll(commentingCount);
        map.putAll(fishCommentCount);
        return map;
    }

    @Override
    public Map<String, Object> findSellerCommentList(CommentInfo commentInfo) {
        List<Map<String, Object>> result = commentDao.findSellerCommentList(commentInfo);
        LOGGER_COMMENTSERVICEIMPL.info("findSellerCommentList >> result.size : " + result.size());
        Map<String, Object> map = new HashMap<>();
        map.put("commentDataList", result);
        return map;
    }

    @Override
	public void delSellerComment(Long detailId,Long commentId) throws Exception{
		Map<String,Object> paramMap=new HashMap<>();
		paramMap.put("detailId", detailId);
		
		//删除回复
		this.delete0(commentDao.delSellerComment(), paramMap);
		
		//删除回复后需要将买家评价置为未回复状态
		 paramMap.put("commentId", commentId);
	        paramMap.put("answerFlag", 0);
	        
	        try {
				
	        	this.update0(commentDao.setValueForAnswerFlag(), paramMap);
			} catch (Exception e) {
	            LOGGER_COMMENTSERVICEIMPL.info("置买家回复标记失败");
	            e.printStackTrace();
	            throw new RuntimeException(e);
			}
		
	}

	@Override
	public void setValueForReadFlag(Long commentId, int objectFlag) throws Exception {
		Map<String,Object> paramMap=new HashMap<>();
		paramMap.put("commentId", commentId);
		paramMap.put("objectFlag", objectFlag);
		
		//置已读标记
		this.update0(commentDao.setValueForAnswerFlag(), paramMap);
		
	}

    @Override
    public List<Map<String, Object>> getDefaultAnswer(CommentInfo commentInfo) {
        return commentDao.getDefaultAnswer(commentInfo);
    }

    @Override
    public void updateRestoreflag(Long commentId,int restoreFlag) throws Exception{
    	Map<String,Object> paramMap=new HashMap<>();
		paramMap.put("commentId", commentId);
		paramMap.put("restoreFlag", restoreFlag);
    	
    	this.update0(commentDao.updateRestoreflag(), paramMap);
    }
}
